﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Text;

using SmartProject.Data;

namespace SmartProject.UI
{
    /// <summary>
    /// The BasePage is used on every page used in SmartProject.
    /// </summary>
    public abstract class BasePage : System.Web.UI.Page
    {
        private static int _userId;
        private static string _fullName;
        private static bool _isFirstTimePreferenceSetup = true;
        private static bool _isFirstTimeUserSetup = true;

        protected override void OnLoad(EventArgs e)
        {
            Log("SetPage", "Page is loaded.", "Debug");
            InitializeUserInfo();
            base.OnLoad(e);
        }

        public string UserName
        {
            get { return this.User.Identity.Name; }
        }

        /// <summary>
        /// Gets the fullname of the user who is currently logged in.
        /// </summary>
        public string FullName
        {
            get
            {
                InitializeUserInfo();
                return _fullName;
            }
        }

        /// <summary>
        /// Gets the user id of the user who is currently logged in.
        /// </summary>
        public int UserId
        {
            get
            {
                InitializeUserInfo();
                return _userId;
            }
        }

        public void InsertNone(ListControl listControl)
        {
            listControl.Items.Insert(0, new ListItem("Select one", "0"));
            listControl.SelectedIndex = 0;
        }

        public void Signout()
        {
            _fullName = String.Empty;
        }

        private void InitializeUserInfo()
        {
            if (String.IsNullOrEmpty(_fullName))
            {
                if (!IsFirstTimeUserSetup)
                {
                    if (!this.User.Identity.Name.StartsWith("Temp_"))
                    {
                        SmartProject.BusinessObjects.User user = new SmartProject.BusinessObjects.User();
                        user.SetAttribute("UserName", this.User.Identity.Name);
                        user.Load();
                        _userId = Convert.ToInt32(user.GetAttributeValue("UserId"));
                        _fullName = user.GetAttributeValue("FirstName").ToString() + " "
                            + user.GetAttributeValue("LastName").ToString();
                        Log("InitializeUserInfo", String.Format("Initializing user, Id={0}, Name={1}",
                            _userId.ToString(), _fullName), "Debug");
                    }
                }
            }
        }

        /// <summary>
        /// Allows you to access the OnLoad event and insert some javascript you
        /// wish to attach to that event.
        /// </summary>
        /// <param name="javaScript">Javascript you wish to insert.</param>
        protected void SetBodyOnLoad(string javaScript)
        {
            HtmlGenericControl html = (HtmlGenericControl)this.Master.FindControl("MasterBody");
            html.Attributes.Add("onload", javaScript);
        }

        /// <summary>
        /// Sets the title and description to display on the page.
        /// </summary>
        /// <param name="title">Title of the page.</param>
        /// <param name="description">A short description of the function of this page.</param>
        protected void SetPage(string title, string description)
        {
            Label lblTitle = (Label)this.Master.FindControl("LblTitle");
            lblTitle.Text = title;
            Label lblDescription = (Label)this.Master.FindControl("LblDescription");
            lblDescription.Text = description;
            HtmlGenericControl lblWarningOrError =
                (HtmlGenericControl)this.Master.FindControl("LblErrorOrWarning");
            lblWarningOrError.Visible = false;
        }

        public string Description
        {
            get
            {
                Label lblDescription = (Label)this.Master.FindControl("LblDescription");
                return lblDescription.Text;
            }
        }

        /// <summary>
        /// Clears the error or warning that is displayed on top of the page.
        /// </summary>
        internal void ClearErrorOrWarning()
        {
            DisplayErrorOrWarning(String.Empty);
        }

        /// <summary>
        /// Sets the error or warning that is display on top of the page.
        /// </summary>
        /// <param name="message">Message to display.</param>
        internal void DisplayErrorOrWarning(string message)
        {
            HtmlGenericControl lblWarningOrError =
                (HtmlGenericControl)this.Master.FindControl("LblErrorOrWarning");
            lblWarningOrError.InnerHtml = message.Replace("\r\n", "<br/>");
            if (String.IsNullOrEmpty(message))
            {
                lblWarningOrError.Visible = false;
            }
            else
            {

                lblWarningOrError.Visible = true;
            }
        }

        /// <summary>
        /// Set a maximum length to a textbox control found on this page.
        /// </summary>
        /// <param name="length">Maximum lenght of the textbox.</param>
        /// <param name="txt">Textbox control to set max length to.</param>
        public void SetMultilineTextBoxMaxLength(int length, TextBox txt)
        {
            StringBuilder js = new StringBuilder("function isMaxLength(txtBox) {");
            js.Append(" if(txtBox) { ");
            js.Append("     return ( txtBox.value.length <=");
            js.Append(length.ToString());
            js.Append(");");
            js.Append(" }");
            js.Append("}");

            txt.Attributes.Add("onkeypress", "try { return isMaxLength(this); } catch{}");
            this.ClientScript.RegisterClientScriptBlock(
                this.GetType(), "txtLength", js.ToString(), true);
        }

        public void Log(string methodName, string description, string severity)
        {
            string className = this.Page.GetType().ToString();
            int userId = _userId;
            if (userId == 0)
            {
                userId = -1;
            }
            Logging.Logger.Log(className, methodName, description, severity, userId);
        }

        /// <summary>
        /// Gets if this is the first time preference setup occurs.
        /// </summary>
        public static bool IsFirstTimePreferenceSetup
        {
            get
            {
                // Only do the calcuations if SmartProject has just been installed.
                if (_isFirstTimePreferenceSetup)
                {
                    // If we were setup already, the preference counts would be > 0.
                    DataHelper dataHelper = new DataHelper();
                    _isFirstTimePreferenceSetup = (dataHelper.GetCounts("smartproject_GetPreferenceCounts") == 0);
                    Logging.Logger.Log("BasePage", "IsPreferenceSetup",
                        String.Format("IsPreferenceSetup={0}", _isFirstTimePreferenceSetup.ToString()), "Debug");
                }
                return _isFirstTimePreferenceSetup;
            }
        }

        /// <summary>
        /// Gets if this is the first time user setup occurs.
        /// </summary>
        public static bool IsFirstTimeUserSetup
        {
            get
            {
                // Only do the calcuations if SmartProject has just been installed.
                if (_isFirstTimeUserSetup)
                {
                    DataHelper dataHelper = new DataHelper();
                    _isFirstTimeUserSetup = (dataHelper.GetCounts("smartproject_GetUserCount") == 0);
                    Logging.Logger.Log("BasePage", "IsUserSetup",
                        String.Format("IsUserSetup={0}", _isFirstTimeUserSetup.ToString()), "Debug");
                }
                return _isFirstTimeUserSetup;
            }
        }

        /// <summary>
        /// Gets if this is the first time management setup has occured.
        /// </summary>
        public bool IsFirstTimeManagementSetup
        {
            get
            {
                DataHelper dataHelper = new DataHelper();
                if (dataHelper.GetCounts("smartProject_GetProductCount") > 0)
                {
                    //if (dataHelper.GetCounts("smartProject_GetSprintCount") > 0)
                    //{
                    BusinessObjects.Category category =
                        new SmartProject.BusinessObjects.Category();
                    if (category.Counts > 0)
                    {
                        return false;
                    }
                    //}
                }

                return true;
            }
        }

        public void GetPreference(string key, out string stringValue, out int intValue)
        {
            UserProfile userProfile = new UserProfile();
            userProfile.SetAttribute("UserId", _userId);
            userProfile.SetAttribute("ProfileName", this.Page.GetType() + key);
            userProfile.Load();

            object objStringValue = userProfile.GetAttributeValue("ProfileStringValue");
            if (objStringValue != null)
            {
                stringValue = (string)objStringValue;
            }
            else
            {
                stringValue = String.Empty;
            }

            object objIntValue = userProfile.GetAttributeValue("ProfileIntValue");
            if (objIntValue != null)
            {
                intValue = (int)objStringValue;
            }
            else
            {
                intValue = 0;
            }
        }

        public void SavePreference(string key, string stringValue, int intValue)
        {
            UserProfile userProfile = new UserProfile();
            userProfile.SetAttribute("UserId", _userId);
            userProfile.SetAttribute("ProfileName", this.Page.GetType() + key);
            userProfile.Load();

            object userId = userProfile.GetAttributeValue("UserId");
            userProfile.SetAttribute("UserId", _userId);
            userProfile.SetAttribute("ProfileName", this.Page.GetType() + key);
            userProfile.SetAttribute("ProfileStringValue", stringValue, false);
            userProfile.SetAttribute("ProfileIntValue", intValue, false);

            if (userId == null)
            {
                userProfile.Save();
            }
            else
            {
                userProfile.Update();
            }
        }

        public abstract void RefreshPage(object obj);

        public abstract AjaxControlToolkit.ModalPopupExtender Popup(string name);
    }
}
